/*
 * @lc app=leetcode.cn id=42 lang=typescript
 *
 * [42] 接雨水
 */

// @lc code=start
function trap(height: number[]): number {
  const stack = [];
  let ans = 0;
  for (let i = 0; i < height.length; i++) {
    while (stack.length && height[i] > height[stack[stack.length - 1]]) {
      const bottom = stack.pop();
      // 栈空了，不能形成凹槽，没法接雨水
      if (stack.length === 0) break;
      let l = height[stack[stack.length - 1]] - height[bottom];
      let r = height[i] - height[bottom];
      // 跨度*高度差，每层接的雨水量
      ans += (i - stack[stack.length - 1] - 1) * Math.min(l, r);
    }
    stack.push(i);
  }
  return ans;
}
// @lc code=end
